package mgr_chat

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"github.com/spf13/cast"
	global2 "longmen/server/config/global"
	"reflect"
)

type History struct {
	Id          string `json:"id"`           // es唯一id
	ChatId      string `json:"chat_id"`      // 聊天id, 房管id_用户id
	SenderUid   int    `json:"sender_uid"`   // 发送用户ID
	ReceiveUid  int    `json:"receive_uid"`  // 接受用户ID
	Avatar      string `json:"avatar"`       // 发送者头像
	Nickname    string `json:"nickname"`     // 发送者昵称
	Content     string `json:"content"`      // 聊天内容
	SendTime    int64  `json:"send_time"`    // 发言时间-秒
	Role        int    `json:"role"`         // 0-普通用户 1-房管
	TextType    int    `json:"text_type"`    // 0-普通消息 1-图文消息 2-删除通知
	ImageUrl    string `json:"image_url"`    // 图片url
	ImageWidth  int    `json:"image_width"`  // 图片宽度
	ImageHeight int    `json:"image_height"` // 图片高度
}

const MgrChatHistoryIndexName = "mgr_history"

const (
	MgrHistoryCommonType = iota
	MgrHistoryImageType
	MgrHistoryDeleteType
)

func (h History) WriteToEs() bool {
	_, err := global2.GetEs().Index().Index(MgrChatHistoryIndexName).Id(h.Id).BodyJson(h).Do(context.Background())
	if err != nil {
		global2.Log.Errorf("err:%v", err)
		return false
	}
	return true
}

func GetHistory(chatId string, page, limit int, delStamp int64) ([]History, int64) {
	start := (page - 1) * limit
	// 聊天排序，查询时按倒序分页, 查出来后再reverse,得出的数据就是按时间正序，最后一条就是最新的
	sort := elastic.NewFieldSort("send_time").Desc()
	query := elastic.NewBoolQuery().Filter(elastic.NewTermQuery("chat_id", chatId))

	if delStamp > 0 {
		query = query.Filter(elastic.NewRangeQuery("send_time").Gt(delStamp))
	}

	res, err := global2.GetEs().Search(MgrChatHistoryIndexName).
		From(start).
		Size(limit).
		PostFilter(query).
		SortBy(sort).
		Do(context.Background())
	if err != nil {
		global2.Log.Errorf("search error: %v", err)
		return nil, 0
	}
	var item History
	records := make([]History, 0)
	for _, v := range res.Each(reflect.TypeOf(item)) {
		records = append(records, v.(History))
	}
	//reverse
	for i, j := 0, len(records)-1; i < j; i, j = i+1, j-1 {
		records[i], records[j] = records[j], records[i]
	}
	return records, res.TotalHits()
}

func DeleteHistory(msgId string) (err error) {
	_, err = global2.GetEs().Delete().Index(MgrChatHistoryIndexName).Id(cast.ToString(msgId)).Refresh("true").Do(context.Background())
	if err != nil {
		global2.Log.Errorf("delete error: %v", err)
	}
	return
}

func GetFromEs(msgId string) (h *History, err error) {
	h = &History{}
	res, err := global2.GetEs().Get().Index(MgrChatHistoryIndexName).
		Id(cast.ToString(msgId)).
		Do(context.Background())
	if err != nil {
		return
	}
	err = json.Unmarshal(res.Source, h)
	return
}
